
@extends('dashboard.includes.master')
@section('title', 'Tempeletes')

@section('css')
<style>
#searchInput {
    max-width: 350px;
    margin: 2rem 2rem 1rem auto !important;
    box-shadow: 0 1px 1px #eee7ee99, 0 -1px 1px #eee7ee99;
}

.sort-icon {
    cursor: pointer;
    margin-left: 5px;
}

.sort-asc::after {
    content: '↑';
}

.sort-desc::after {
    content: '↓';
}

.sort-none::after {
    content: '↕';
}

th.sortable {
    cursor: pointer;
    user-select: none;
}

.table {
    width: 100%;
    border-collapse: collapse;
}

.table th,
.table td {
    border: 1px solid #ddd;
    padding: 8px;
}

.table th {
    background-color: #f2f2f2;
}

.pagination {
    margin-top: 10px;
}

.pagination .page-link {
    margin: 0 5px;
}

.table td a {
    color: blue;
    text-decoration: underline;
}

.table td h1 {
    font-size: 1.5em;
    margin: 0.5em 0;
    font-weight: bold;
}

.table td code {
    background-color: #f4f4f4;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: monospace;
}

.preview-iframe {
    width: 100%;
    min-height: 150px; /* Increased for better visibility */
    border: none;
}
</style>
@endsection

@section('content')
<div class="col-xl-12">
    <div class="row">
        <div class="col-xl-12">
            <div class="card custom-card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <div class="d-flex">
                        <a href="{{ route('tempelete.create') }}" class="btn btn-primary btn-sm me-2">
                            <i class="ri-add-line"></i> Add Tempelete
                        </a>
                    </div>
                </div>

                <input type="text" id="searchInput" class="form-control"
                    placeholder="Search by subject or body...">

                <div class="card-body">
                    @if(session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        {{ session('success') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    @endif

                    @if(session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('error') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    @endif

                    <table id="file-export" class="table table-bordered text-nowrap w-100">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th class="sortable" data-sort="subject">Subject <span class="sort-icon sort-none"></span></th>
                                <th class="sortable" data-sort="body">Body <span class="sort-icon sort-none"></span></th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="tempeleteTableBody">
                            @forelse($tempeletes as $tempelete)
                            <tr class="product-list" data-body="{{ htmlentities($tempelete->body) }}">
                                <td>
                                    @if($tempeletes instanceof \Illuminate\Pagination\LengthAwarePaginator)
                                        {{ ($tempeletes->currentPage() - 1) * $tempeletes->perPage() + $loop->index + 1 }}
                                    @else
                                        {{ $loop->index + 1 }}
                                    @endif
                                </td>
                                <td>{{ $tempelete->subject ?? 'N/A' }}</td>
                                <td>
                                    @if(preg_match('/<!DOCTYPE\s+html>|<html[\s\S]*>/i', $tempelete->body))
                                        <iframe class="preview-iframe" style="width: 100%; min-height: 150px; border: none;" sandbox="allow-same-origin"></iframe>
                                        <script>
                                               {!! html_entity_decode($tempelete->body) !!}
                                        </script>
                                    @else
                                        {!! html_entity_decode($tempelete->body) !!}
                                    @endif
                                </td>
                                <td>
                                    <div class="hstack gap-2 fs-15">
                                        <form action="{{ route('tempelete.edit', $tempelete->id) }}" method="GET"
                                            style="display:inline;">
                                            @csrf
                                            <input type="hidden" name="id" value="{{ $tempelete->id }}">
                                            <button type="submit" class="btn btn-icon btn-sm btn-info-light"
                                                title="Edit Tempelete">
                                                <i class="ri-edit-line"></i>
                                            </button>
                                        </form>
                                        <button type="button" class="btn btn-icon btn-sm btn-danger delete-button"
                                            data-bs-toggle="modal" data-bs-target="#deleteModal{{ $tempelete->id }}"
                                            data-id="{{ $tempelete->id }}">
                                            <i class="ri-delete-bin-line"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <div class="modal fade" id="deleteModal{{ $tempelete->id }}" tabindex="-1"
                                aria-labelledby="deleteModalLabel" aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="deleteModalLabel">Confirm Deletion</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                                aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            Are you sure you want to delete this item?
                                        </div>
                                        <div class="modal-footer">
                                            <form id="deleteForm{{ $tempelete->id }}" method="POST"
                                                action="{{ route('tempelete.destroy', $tempelete->id) }}">
                                                @csrf
                                                @method('DELETE')
                                                <input type="hidden" name="id" id="id" value="{{ $tempelete->id }}">
                                                <button type="button" class="btn btn-secondary"
                                                    data-bs-dismiss="modal">Cancel</button>
                                                <button type="submit" class="btn btn-danger">Delete</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            @empty
                            <tr>
                                <td colspan="4" class="text-center">No Tempeletes found.</td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                    @if($tempeletes instanceof \Illuminate\Pagination\LengthAwarePaginator)
                    <div class="d-flex justify-content-center mt-3 pagination">
                        {{ $tempeletes->links('vendor.pagination.bootstrap-4') }}
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('js')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const sortableHeaders = document.querySelectorAll('th.sortable');
    sortableHeaders.forEach(header => {
        header.addEventListener('click', function() {
            const sortKey = this.getAttribute('data-sort');
            const sortIcon = this.querySelector('.sort-icon');
            let sortDirection = sortIcon.classList.contains('sort-asc') ? 'desc' : 'asc';

            document.querySelectorAll('.sort-icon').forEach(icon => {
                icon.classList.remove('sort-asc', 'sort-desc');
                icon.classList.add('sort-none');
            });

            sortIcon.classList.remove('sort-none');
            sortIcon.classList.add(`sort-${sortDirection}`);

            const tableBody = document.getElementById('tempeleteTableBody');
            const rows = Array.from(tableBody.querySelectorAll('tr'));
            rows.sort((a, b) => {
                let aValue = sortKey === 'subject' 
                    ? a.querySelector('td:nth-child(2)').innerText
                    : a.getAttribute('data-body');
                let bValue = sortKey === 'subject' 
                    ? b.querySelector('td:nth-child(2)').innerText
                    : b.getAttribute('data-body');
                return sortDirection === 'asc'
                    ? aValue.localeCompare(bValue)
                    : bValue.localeCompare(aValue);
            });
            tableBody.innerHTML = '';
            rows.forEach(row => tableBody.appendChild(row));
        });
    });

    const searchInput = document.getElementById('searchInput');
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        const rows = document.querySelectorAll('#tempeleteTableBody tr');
        rows.forEach(row => {
            const subject = row.querySelector('td:nth-child(2)').innerText.toLowerCase();
            const body = row.getAttribute('data-body').toLowerCase();
            row.style.display = (subject.includes(searchTerm) || body.includes(searchTerm))
                ? ''
                : 'none';
        });
    });
});
</script>
@endsection
